/**
 * @autor wonderful 20190620
 * @description 首页页面交互及业务逻辑
 */
//根据浏览器窗让体大小，改变上左右容器盒子的大小。
function resizeBoxs(){
   var winHeight=$(window).height();
   var winWidth=$(window).width();
   var leftBox=$(".leftBox");
   var rightBox=$(".rightBox");
   var topBar=$(".topBar");
   var realLRHeight=winHeight-130;
   var realLRWidth=winWidth-360;
   leftBox.height(realLRHeight-30);
   leftBox.width(realLRWidth);
   leftBox.find("#map").height(realLRHeight-40);
   leftBox.find("#map").width(realLRWidth-10);
   rightBox.height(realLRHeight);
   rightBox.find(".eventsList").height(realLRHeight-193);
   rightBox.find(".eventsList .content").height(realLRHeight-193-39);
   rightBox.find(".eventsList .content .list").height(realLRHeight-193-39);
   topBar.width(winWidth-40);
   // console.log(winHeight+","+winWidth);
}

/*************************地图相关BEGIN****************************/
//地图坐标点分类聚合
function pointsClusterer(){
    map.setMapStyle({style:'grayscale'});
    var markers_kfc = [];
    var markers_mcd = [];

    queue()
        .defer(d3.csv, 'data/kfc_official.csv')
        .defer(d3.csv, 'data/mcd_official_geo.csv')
        .await(function(error, kfc, mcd) {
            kfc.forEach(function(d) {
                var pt = new BMap.Point(d.lng, d.lat);
                markers_kfc.push(new BMap.Marker(pt));
            });
            mcd.forEach(function(d) {
                var pt = new BMap.Point(d.lng, d.lat);
                markers_mcd.push(new BMap.Marker(pt));
            });
            var markerClusterer_kfc = new BMapLib.MarkerClusterer(map, {markers:markers_kfc});
            var markerClusterer_mcd = new BMapLib.MarkerClusterer(map, {markers:markers_mcd});
        });
}
/*************************地图相关END****************************/

/*************************设备状态监控面板begin****************************/
var deviceMointorPanelOpt={
    ipcChartId:"ipcChart",
    batteryChartId:"batteryChart",
    upsAChartId:"upsAChart",
    fourAChartId:"fourWaysAChart",
    fourVChartId:"fourWaysVChart",
    tahChartId:"tahChart",
    deviceId:1
}
/***************************设备状态监控面板end****************************/

/*************************业务相关BEGIN****************************/
//初始化绑定异常事件类型数据到过滤操作元素
function initEventTypeFilters(){
    $(".eventFilterBox .item").each(function(i,obj){
        var item=$(obj);
        item.bind("click",showEventsToMap);
        if(item.attr("class").indexOf("temperature")!=-1){
             item.data("eventTypeId",EVENTTYPE_TEMPERATURE);
        }else if(item.attr("class").indexOf("inundate")!=-1){
            item.data("eventTypeId",EVENTTYPE_INUNDATE);
        }else if(item.attr("class").indexOf("outage")!=-1){
            item.data("eventTypeId",EVENTTYPE_OUTAGE);
        }else if(item.attr("class").indexOf("offline")!=-1){
            item.data("eventTypeId",EVENTTYPE_OFFLINE);
        }else if(item.attr("class").indexOf("fire")!=-1){
            item.data("eventTypeId",EVENTTYPE_FIRE);
        }else if(item.attr("class").indexOf("device")!=-1){
            item.data("eventTypeId",EVENTTYPE_DEVICE);
        }
    });
}
var markers=[];
var markerClusterer=null;
//获取地图标注消息窗口
function getInfoWindow(info,windowTemplateId){
    var temp=$("#"+windowTemplateId);
   for(var key in info){
       temp.find("#"+key).text(info[key]);
   }
    temp.css("display","block");
   var content=temp.html();
    temp.css("display","none");
   return content;
}

function showEventsToMap(){
    $(this).parent().find(".item").removeClass("eventFilterItemChoice");
    $(this).addClass("eventFilterItemChoice");
    if(markerClusterer==null)
    markerClusterer  = new BMapLib.MarkerClusterer(map, {markers:markers});
    var eventTypeId=$(this).data("eventTypeId");
    markers=[];
    /*  //清除覆盖物
      map.clearOverlays();*/
    //清除聚合点
    markerClusterer.clearMarkers(markers);
    $.ajax({
        url: basePath+"/event/listEventsByEventType",
        //processData: false,
        //data: xmlDocument,
        async: true,
        dataType: "json",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        // data: encodeURI(option.param),//解决页面默认为GBK编码导致的Ajax传输中文乱码问题
        data: {
            eventTypeIds:eventTypeId
        },
        beforeSend: null,
        success: function (data) {
            if(data.status==1){

               var events=data.data;

               for(var i=0;i<events.length;i++){

                   var event=events[i];
                   var pt = new BMap.Point(event.deviceLng, event.deviceLat);
                   var marker=new BMap.Marker(pt);

                   var deviceIds=event.deviceId;

                   //防止对象引用异常
                   function getMarkClickEvent(deviceIds){
                       var deviceId=deviceIds;
                       return function(){
                           var marker=this;
                           $.ajax({
                           url: basePath+"/deviceStatus/listDeviceStatus",
                           //processData: false,
                           //data: xmlDocument,
                           async: true,
                           dataType: "json",
                           type: "POST",
                           contentType: "application/x-www-form-urlencoded",
                           // data: encodeURI(option.param),//解决页面默认为GBK编码导致的Ajax传输中文乱码问题
                           data: {
                               deviceIds:deviceId
                           },
                           beforeSend: null,
                           success: function (data) {
                               if(data.status==1){
                                   var deviceStatus=data.data;
                                   var info={
                                       deviceNo:deviceIds,//设备编号
                                       temperature:"1",//设备温度
                                       humidity:"0%"//设备湿度
                                       // warning:"30"//设备预警次数
                                   };
                                   $(deviceStatus).each(function(i,obj){

                                       if(obj.deviceStatusId==DEVICESTATUS_ENVNODETEMPERATURE){
                                           info.temperature=obj.deviceStatusValue+obj.deviceStatusUnit;
                                       }else if(obj.deviceStatusId==DEVICESTATUS_ENVNODEHUMIDITY){
                                           info.humidity=obj.deviceStatusValue+obj.deviceStatusUnit;
                                       }

                                   });

                                   var content=getInfoWindow(info,"infoWindow1");
                                   var infoWindow= new BMap.InfoWindow(content, {
                                       enableMessage : false,
                                       width : 130,
                                       height :116,
                                       title :"设备状态"
                                   });
                                   //标注信息窗体自定义详细按钮事件绑定
                                   infoWindow.addEventListener("open", function (e) {
                                       $("#gisDeviceDetial").unbind("click");
                                       $("#gisDeviceDetial").click(function () {
                                          var template=$(this).parent().parent();
                                           deviceMointorPanelOpt.deviceId=template.find("#deviceNo").text();
                                           $("#test").monitorPanel("init",deviceMointorPanelOpt);

                                   }) });
                                   marker.openInfoWindow(infoWindow);
                               }
                           },
                           error: function (XMLHttpRequest, textStatus, errorThrown) {

                           }});
                       }
                   }
                   marker.addEventListener("click",getMarkClickEvent(deviceIds));
                   markers.push(marker);
               }
                markerClusterer.addMarkers(markers);
                map.centerAndZoom("贵州", 9);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

        }
    });
}
//列表展示最新的事件
function listEvents(){
    $.ajax({
        url: basePath+"/event/listEventsByEventType",
        //processData: false,
        //data: xmlDocument,
        async: true,
        dataType: "json",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        // data: encodeURI(option.param),//解决页面默认为GBK编码导致的Ajax传输中文乱码问题
        data: {
            eventTypeIds:EVENTTYPE_TEMPERATURE+
                ","+EVENTTYPE_INUNDATE+
                ","+EVENTTYPE_OUTAGE+
                ","+EVENTTYPE_OFFLINE+
                ","+EVENTTYPE_FIRE+
                ","+EVENTTYPE_DEVICE,
            isTop:true,
            topNum:100//获取最近的100条异常纪录
        },
        beforeSend: null,
        success: function (data) {

            if(data.status==1){
                var events=data.data;
                for(var i=0;i<events.length;i++) {
                    var event = events[i];
                    var tabList=$(".eventsList #list2");
                    var item=$("<div class='item'></div>").appendTo(tabList);
                    var msg=$("<div class='msg'></div>").appendTo(item);
                    var icon=$("<div class='icon'></div>").appendTo(msg);
                    var text=$("<div class='text'>"+event.eventMsg+"</div>").appendTo(msg);
                    var time=$("<div class='time'>"+event.diffMinute+"分钟前</div>").appendTo(item);
                    var detail=$("<div class='detail'>查看详细</div>").appendTo(item);
                    detail.data("event",event);
                    detail.bind("click",function(){
                        deviceMointorPanelOpt.deviceId=$(this).data("event").deviceId;
                        $("#test").monitorPanel("init",deviceMointorPanelOpt);
                    });
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

        }});
}

//根据事件类型显示发生对应事件的设备数量
function showDeviceCountByEventType(){
    $(".topBox .eventsStatisticBox .text").text(0);
    $.ajax({
        url: basePath+"/event/getDeviceCountByEventType",
        //processData: false,
        //data: xmlDocument,
        async: true,
        dataType: "json",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        // data: encodeURI(option.param),//解决页面默认为GBK编码导致的Ajax传输中文乱码问题
        data: {
            eventTypeIds:EVENTTYPE_TEMPERATURE+
                ","+EVENTTYPE_INUNDATE+
                ","+EVENTTYPE_OUTAGE+
                ","+EVENTTYPE_OFFLINE+
                ","+EVENTTYPE_FIRE+
                ","+EVENTTYPE_DEVICE
        },
        beforeSend: null,
        success: function (data) {

            if(data.status==1){
                var events=data.data;
                for(var i=0;i<events.length;i++) {
                    var event = events[i];
                    if(event.eventTypeId==EVENTTYPE_TEMPERATURE){
                        $(".topBox .temperature .text").text(event.deviceCount);
                    }else if(event.eventTypeId==EVENTTYPE_INUNDATE){
                        $(".topBox .inundate .text").text(event.deviceCount);
                    }else if(event.eventTypeId==EVENTTYPE_OUTAGE){
                        $(".topBox .outage .text").text(event.deviceCount);
                    }else if(event.eventTypeId==EVENTTYPE_OFFLINE){
                        $(".topBox .offline .text").text(event.deviceCount);
                    }else if(event.eventTypeId==EVENTTYPE_FIRE){
                        $(".topBox .fire .text").text(event.deviceCount);
                    }else if(event.eventTypeId==EVENTTYPE_DEVICE){
                        $(".topBox .device .text").text(event.deviceCount);
                    }
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

        }});

}

/*************************业务相关END*****************************/

//页面加载各项元素、数据初始化
$("body").ready(function(){
    $(window).resize(resizeBoxs);
    resizeBoxs();
    $($(".eventsList .tab")[0]).click();
    initEventTypeFilters();
    listEvents();
    showDeviceCountByEventType();
});